package com.seestech.sell.web.agent;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.ExcelExport;
import com.seestech.sell.common.utils.JsonUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.domain.model.Agent;
import com.seestech.sell.domain.model.Error;
import com.seestech.sell.domain.model.ResultBean;
import com.seestech.sell.domain.model.enums.ExcelTypeEnums;
import com.seestech.sell.domain.model.vo.AgentVoExcel;
import com.seestech.sell.domain.model.vo.ErrorVoExcel;
import com.seestech.sell.service.IAgentService;
import com.seestech.sell.service.IErrorService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by idiot on 2017/8/1.
 */
@Controller
@RequestMapping(value = "agent/error")
public class ErrorController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(ErrorController.class);

    @Resource
    private IAgentService agentService;
    @Resource
    private IErrorService errorService;

    //文件名
    private static String errorListFile = "error_list.xlsx";

    // 加载终端异常页面
    @RequiresPermissions(value = "agent:error:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String page(){
        return "agent/error/page";
    }

    @RequestMapping(value = "data")
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize,
                     Error info, Model model){
        Page<Error> errors = errorService.getAllErrors(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", errors);
        return "agent/error/data";
    }


    /**********************  接口  *************************/

    @ResponseBody
    @RequestMapping(value = "getErrorsByAgentId.json")
    public Object getErrorsByAgentId(Long agentId){
        logger.info("获取终端异常列表===============>>>>>>>>开始");
        ResultBean<Object> resultBean;
        Agent agent = agentService.getAgentByAgentId(agentId);
        if(agent == null){
            logger.error("获取终端异常列表===============>>>>>>>>无效的agentId"+agentId);
            resultBean = ResponseUtils.initResultBean(null, Constants.ResponseCode.error, "无效的agentId", false);
        }else {
            List<Error> errors = errorService.getErrorsByAgentId(agent.getAgentId());
            //处理long类型
            JSONArray object = JsonUtils.parseArray(errors);
            resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
        }
        logger.info("获取终端异常列表===============>>>>>>>>结束");
        return resultBean;
    }


    /**
     * 数据导出
     * @param
     * @param info
     * @return
     * @throws FileNotFoundException
     */
    @ResponseBody
    @RequestMapping(value = "exportData.json", method = RequestMethod.POST)
    public String exportData(Error info) throws FileNotFoundException {
        //项目访问路径
        String serverPath = request_local.get().getScheme() + "://" + request_local.get().getServerName() + ":" +
                request_local.get().getServerPort() + request_local.get().getContextPath() + "/";
        //获取数据
        List<ErrorVoExcel> list = errorService.getAllExportErrors(new RowBounds(), info);
        // 写入excel文件
        File file = new File(Thread.currentThread().getContextClassLoader().getResource("/templates").getPath()+ errorListFile);
        OutputStream  out = new FileOutputStream(file);
        ExcelExport.exportExcel("终端异常列表", AgentVoExcel.class, list, out, ExcelTypeEnums.XLSX);
        //返回下载文件地址
        return ResponseUtils.responseSuccess(serverPath + errorListFile);
    }
}
